package service;

import dao.UserDao;
import entity.User;
import util.BCryptUtil;

import java.util.List;

public class UserService {
    private final UserDao userDao = new UserDao();

    public boolean register(String userName, String password, String role) {
        if (userDao.findByUserName(userName) != null) {
            return false;
        }

        String encryptedPassword = BCryptUtil.hashPassword(password); // 加密

        User user = new User();
        user.setUserName(userName);
        user.setPassword(encryptedPassword);
        user.setRole(role);

        userDao.register(user);
        return true;
    }

    public User login(String userName, String password) {
        User user = userDao.findByUserName(userName);
        if (user == null || !BCryptUtil.checkPassword(password, user.getPassword())) {
            return null;
        }
        return user;
    }

    public User getUserById(int userId){
        return userDao.getUserById(userId);
    }

    public boolean isFollowing(int followerId, int followeeId) {
        return userDao.isFollowing(followerId, followeeId);
    }

    public boolean toggleFollowAuthor(int followerId, int followeeId) {
        if (userDao.isFollowing(followerId, followeeId)) {
            userDao.unfollowUser(followerId, followeeId);
            return true;
        }else{
            userDao.followUser(followerId, followeeId);
            return false;
        }
    }

    public List<User> searchUsersByKeyword(String keyword) {
        return userDao.searchUsersByKeyword(keyword);
    }

    public List<User> getFolloweeUsers(int userId) {
        return userDao.getFolloweeUsers(userId);
    }
}

